const { Service } = require('egg');
module.exports = class extends Service {
    async index(query) {
        const { app } = this;
        let { current, pageSize, sort, order, created, ...where } = query;
        current = isNaN(current) ? 1 : Number(current);
        pageSize = isNaN(pageSize) ? 10 : Number(pageSize);
        const offset = (current - 1) * pageSize;
        let { fields = "{}", page = "{}", record = "{}" } = await app.mysql.get('entity', { name: this.entity }) || {};
        fields = JSON.parse(fields);
        page = JSON.parse(page);
        record = JSON.parse(record);
        if (created) {
            const filterFields = Object.entries(where).map(([key, value]) => `${key}='${value}'`);
            const [startTime, endTime] = created.split(',');
            filterFields.push(`created between '${startTime}' and '${endTime}'`);
            let filterSQL = '';
            if (filterFields.length > 0) {
                filterSQL = `where ${filterFields.join(' and ')}`;
            }
            const [{ total }] = await app.mysql.query(`SELECT count(*) as total FROM ${this.entity} ${filterSQL}`);
            if (sort && order) {
                filterSQL += ` order by ${sort} ${order} `;
            }
            if (current && pageSize) {
                filterSQL += ` limit ${offset}, ${pageSize} `;
            }
            const list = await app.mysql.query(`SELECT * FROM ${this.entity} ${filterSQL}`);
            return {
                list,
                total,
                current,
                pageSize,
                fields,
                page,
                record
            };
        } else {
            const options = { where };
            if (pageSize) {
                options.offset = offset;
                options.limit = pageSize;
            }
            if (sort && order) {
                options.orders = [[sort, order]];
            }
            const list = await app.mysql.select(this.entity, options);
            const total = await app.mysql.count(this.entity, where);
            return {
                list,
                total,
                current,
                pageSize,
                fields,
                page,
                record
            };
        }
    }
    async create(entity) {
        const { app } = this;
        entity.created = app.mysql.literals.now
        entity.updated = app.mysql.literals.now
        delete entity.id;
        return await this.app.mysql.insert(this.entity, entity);
    }
    async show(id) {
        let entity = await this.app.mysql.get(this.entity, { id });
        return entity
    }
    async update(entity) {
        delete entity.created;
        delete entity.updated;
        return await this.app.mysql.update(this.entity, entity);
    }
    async delete(ids) {
        return await this.app.mysql.delete(this.entity, { id: ids });
    }
}
